package net.simflow.swf.analyzer.bggraph.opt;

import java.util.Collection;
import java.util.HashSet;

import net.simflow.swf.analyzer.bgnetwork.data.BGLink;
import net.simflow.swf.analyzer.bgnetwork.data.BGNetwork;
import net.simflow.swf.analyzer.bgnetwork.data.BGNode;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseGraph;

public class BGGraphMaker {

	private static BGGraphMaker instance = new BGGraphMaker();

	private BGGraphMaker() {
	}

	public static BGGraphMaker getInstance() {
		return instance;
	}

	public Graph<BGNode, BGLink> make(BGNetwork network, boolean hasAcnode) {
		HashSet<BGNode> set = new HashSet<BGNode>();

		set.addAll(network.getFlowMap().values());
		set.addAll(network.getServiceMap().values());

		return make(set, hasAcnode);
	}

	public Graph<BGNode, BGLink> make(Collection<? extends BGNode> set,
			boolean hasAcnode) {
		Graph<BGNode, BGLink> g = new SparseGraph<BGNode, BGLink>();

		for (BGNode n : set) {
			if (!hasAcnode) {
				if (n.getNeighborSet().isEmpty()) {
					continue;
				}
			}
			g.addVertex(n);
		}

		for (BGNode p : g.getVertices()) {
			for (BGNode c : p.getNeighborSet()) {
				g.addEdge(new BGLink(p, c), p, c);
			}
		}

		return g;
	}

	public Graph<BGNode, BGLink> makeNeighbor(BGNode node) {
		if (node == null) {
			return null;
		}

		Graph<BGNode, BGLink> g = new SparseGraph<BGNode, BGLink>();

		g.addVertex(node);
		for (BGNode n : node.getNeighborSet()) {
			g.addVertex(n);
			g.addEdge(new BGLink(node, n), node, n);
		}

		return g;
	}
}
